package com.lzk.pet.service.imp;


import com.lzk.basic.excption.BusinessException;
import com.lzk.basic.service.IBaiduAiAuditService;
import com.lzk.basic.service.impl.BaseServiceImpl;
import com.lzk.basic.util.CodeGenerateUtils;
import com.lzk.basic.util.DistanceUtils;
import com.lzk.basic.util.PageList;
import com.lzk.basic.util.Point;
import com.lzk.order.domain.OrderPetAcquisition;
import com.lzk.order.mapper.OrderPetAcquisitionMapper;
import com.lzk.org.domain.Employee;
import com.lzk.org.domain.Shop;
import com.lzk.org.mapper.EmployeeMapper;
import com.lzk.org.mapper.ShopMapper;
import com.lzk.pet.domain.Pet;
import com.lzk.pet.domain.SearchMasterMsg;
import com.lzk.pet.domain.SearchMasterMsgAuditLog;
import com.lzk.pet.dto.AcceptDto;
import com.lzk.pet.mapper.PetMapper;
import com.lzk.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.lzk.pet.mapper.SearchMasterMsgMapper;
import com.lzk.pet.query.SearchMasterMsgQuery;
import com.lzk.pet.rocketmq.RocketMQProducer;
import com.lzk.pet.service.ISearchMasterMsgService;
import com.lzk.user.domain.User;
import com.lzk.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private RocketMQProducer rocketMQProducer;
    /**
     * 寻主业务实现
     * @param smm
     * @param id
     */
    @Override
    @Transactional
    public void publish(SearchMasterMsg smm, Long id) {
        /*
            1.先添加到数据库t_searchMasterMsg
            处理user_id shop_id
         */
        User user = userMapper.loadByLogininfoId(id);
        smm.setUser_id(user.getId());

        //先计算最近距离的店铺
        //获取当前地址的point
        Point point = DistanceUtils.getPoint(smm.getAddress());
        Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
        smm.setShop_id(nearestShop.getId());

        searchMasterMsgMapper.save(smm);

        //进行审核
        Boolean textBoo = baiduAiAuditService.textAudit(smm.getName() + smm.getTitle() + smm.getCoat_color() + smm.getAddress());
       /* Boolean imgBoo = baiduAiAuditService.imageAudit(smm.getResources());*/
        if(textBoo){
            //审核通过，修改状态
            smm.setState(1);
            smm.setNote("待处理");
            searchMasterMsgMapper.update(smm);
            //添加审核日志
            SearchMasterMsgAuditLog smmal = new SearchMasterMsgAuditLog();
            smmal.setMsg_id(smm.getId());
            smmal.setState(1);
            smmal.setNote("待处理");
            //保存审核日志
            searchMasterMsgAuditLogMapper.save(smmal);

            //发送短信或邮箱给分配的店铺

        }else {//审核失败
            //1.修改状态
            smm.setNote("驳回,内容违规");
            searchMasterMsgMapper.update(smm);
            //2.添加审核日志
            SearchMasterMsgAuditLog smmal = new SearchMasterMsgAuditLog();
            smmal.setMsg_id(smm.getId());
            smmal.setState(0);
            smmal.setNote("审核不通过，驳回，信息异常");
            searchMasterMsgAuditLogMapper.save(smmal);
            throw new BusinessException("信息异常，请重新输入");

        }
    }

    /**
     * 待审核业务
     * @param searchMasterMsgQuery
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> Pending(SearchMasterMsgQuery searchMasterMsgQuery,Long id) {
        Employee employee = employeeMapper.loadByLogininfoId(id);
        if(employee.getShop_id()==null){
            searchMasterMsgQuery.setState(0);
            return super.queryData(searchMasterMsgQuery);
        }
        return new PageList<>();
    }

    /**
     * 待处理业务
     * @param searchMasterMsgQuery
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> handle(SearchMasterMsgQuery searchMasterMsgQuery,Long id) {
        searchMasterMsgQuery.setState(1);
        //判断是店铺管理员还是后台管理员
        Employee employee = employeeMapper.loadByLogininfoId(id);
        if(employee.getShop_id() !=null ){
            searchMasterMsgQuery.setShop_id(employee.getShop_id());
        }
        return super.queryData(searchMasterMsgQuery);
    }

    /**
     * 拒单
     * @param id
     */
    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    /**
     * 接单
     * @param dto
     */
    @Override
    @Transactional
    public void accept(AcceptDto dto) {
        Long handler = dto.getHandler();
        Long msgId = dto.getMsgId();
        String note = dto.getNote();

        // 根据msgId，如果查的到，该订单正在处理中
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgId(msgId);
        if(order !=null ){
            throw new BusinessException("订单正在处理中");
        }
        //  1. 生成一个pet : 根据searchMasterMsg生成
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        Pet pet = searchMasterMsg2Pet(searchMasterMsg);
        //保存pet
        petMapper.save(pet);

        //生成一个收购订单
        OrderPetAcquisition opa = initOrderPetAcquisition(dto,pet,searchMasterMsg);

        // 保存订单
        orderPetAcquisitionMapper.save(opa);
        //发送延迟消息，假装两天后接收到
        rocketMQProducer.sendDelayMsg(opa.getOrderSn(),3);

    }

    /**
     * 利用工具类生成订单编号
     * @param dto
     * @param pet
     * @param smm
     */
    private OrderPetAcquisition initOrderPetAcquisition(AcceptDto dto, Pet pet, SearchMasterMsg smm) {
        //创建一个订单对象
        OrderPetAcquisition order = new OrderPetAcquisition();

        // 随机生成一个订单编号
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(smm.getUser_id()));
        // 摘要
        order.setDigest("【"+smm.getTitle()+"】");
        // 最后确认时间 定时任务
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        order.setState(0);// 待处理
        order.setPrice(smm.getPrice());
        order.setPet_id(pet.getId());
        order.setUser_id(smm.getUser_id());
        order.setShop_id(smm.getShop_id());
        order.setAddress(smm.getAddress());
        order.setEmp_id(dto.getHandler());
        order.setSearch_master_msg_id(dto.getMsgId());
        return order;
    }

    /**
     * 根据searchMasterMsg生成pet表
     * @param smm
     * @return
     */
    private Pet searchMasterMsg2Pet(SearchMasterMsg smm) {
        Pet pet = new Pet();
        pet.setName(smm.getName());
        pet.setCostprice(smm.getPrice());
        pet.setType_id(smm.getPet_type());
        pet.setResources(smm.getResources());
        pet.setShop_id(smm.getShop_id());
        pet.setSearch_master_msg_id(smm.getId());
        return pet;
    }
}
